import Vue from 'vue'
import VueRouter from 'vue-router'

import Register from '@/views/Register'
import Login from '@/views/Login'
import Layout from '@/views/layout/index.vue'
import Err from '@/views/err/404.vue'
import store from '@/store/index'

import Home from "@/views/layout/home/index.vue"
import UserInfo from '@/views/layout/userInfo/index.vue'
import UserAvatar from "@/views/layout/userAvatar/index.vue"
import UserPassword from '@/views/layout/userPassword/index.vue'
import ArtCate from '@/views/layout/Article/index.vue'
import ArtList from '@/views/layout/Article/ArtList.vue'
Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => err)
}

const routes = [{
    path: "/",
    component: Layout,
    redirect: '/home',
    children: [{
        path: "home",
        component: Home
      },
      {
        path: "user-info",
        component: UserInfo,
      },
      {
        path: "user-avatar",
        component: UserAvatar
      },
      {
        path: "user-pwd",
        component: UserPassword
      },
      {
        path: 'art-cate',
        component: ArtCate
      },
      {
        path: "art-list",
        component: ArtList
      }
    ]
  },
  {
    path: '/register',
    component: Register
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '*',
    component: Err
  },
]

const router = new VueRouter({
  mode: "history",
  routes
})

// 白名单
const whiteList = ['/login', '/register', '*']
//  在没有 token 的时候，掌握如何处理页面的访问权限
router.beforeEach((to, from, next) => {
  // 获取token
  const {
    token
  } = store.state.user
  // 如果有token，直接放行
  if (token) {
    next()
    // 如果没有token
  } else {

    if (whiteList.includes(to.path)) {
      // 要去的路径在白名单中
      // 就放行
      next()
    } else {
      // 要去的路径是 后台主页，强制跳转到登录页
      next('/login')

    }
  }
})

export default router
